package com.dream.controller;

import com.dream.bean.Book;
import com.dream.bean.Page;
import com.dream.service.BookService;
import com.dream.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 匠人码农
 * @date 2020/12/06 10:59
 * 概要：
 *    首页Web层
 */
@Controller
@RequestMapping("/client")
public class ClientBookController {

    /**
     * 首页页面
     */
    private static final String INDEX = "/client/index";

    @Autowired
    BookService bookService;

    /**
     *  首页分页
     * @param model  model
     * @param req    请求
     * @return       分页后的首页
     */
    @RequestMapping("/page")
    public String page(Model model, HttpServletRequest req){

        //获取pageNo和pageSize参数
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);

        //调用service
        Page<Book> page = bookService.page(pageNo,pageSize);

        //分页条url设定
        page.setUrl("client/page");

        //回传数据
        model.addAttribute("page",page);

        //返回主页
        return INDEX;

    }

    /**
     * 价格区间分页
     * @param model model
     * @param req   请求
     * @return      首页按照价格分页
     */
    @RequestMapping("/pageByPrice")
    public String pageByPrice(Model model,HttpServletRequest req) {

        //获取pageNo和pageSize参数

        String minPriceTemp = req.getParameter("minPrice");
        String maxPrinceTemp = req.getParameter("maxPrice");
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int minPrice = WebUtils.parseInt(minPriceTemp,0);
        int maxPrice = WebUtils.parseInt(maxPrinceTemp,Integer.MAX_VALUE);

        //调用service
        Page<Book> page = bookService.page(pageNo,pageSize,minPrice,maxPrice);

        //分页条url设定
        StringBuilder sb= new StringBuilder("client/pageByPrice");

        //最小价格不为null

        if(null != minPriceTemp){
            sb.append("?minPrice=").append(minPrice);
        }

        //最大价格不为null

        if(null != maxPrinceTemp){
            sb.append("&maxPrice=").append(maxPrice);
        }

        page.setUrl(sb.toString());

        //回传数据
        model.addAttribute("page",page);

        //返回页面
        return INDEX;

    }
}
